package com.anysoft.rrm;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.anysoft.util.Properties;

/**
 * 管理器
 * @author duanyy
 * @version 1.6.4.14 [20151126 duanyy] <br>
 * - 增加list方法.<br>
 * 
 * @version 1.9.6.7 [20170802 duanyy] <br>
 * - 修正多实例下的并发问题 <br>
 * 
 * @version 1.6.12.32 [20190429] <br>
 * - 优化RRM模型
 * 
 */
public class RRModelManager  {
	public static final String DEFAULT =
			"java:///com/anysoft/rrm/default.xml#" + RRModelManager.class.getName();

	private Map<String,RRModel<RRData>> rrms = new ConcurrentHashMap<String,RRModel<RRData>>();
	
	public RRModel<RRData> getModel(String id){
		return rrms.get(id);
	}

	public void addModel(RRData instance,Properties p){
		String id = instance.id();
		RRModel<RRData> found = getModel(id);
		if (found == null){
			synchronized (this) {
				found = getModel(id);
				if (found == null) {
					found = new RRModel<RRData>(id);
					found.configure(p);
					rrms.put(id, found);
				}
			}
		}
		found.update(System.currentTimeMillis(), instance);
	}	

	public void remove(String id){
		rrms.remove(id);
	}
		
	public void clear(){
		rrms.clear();
	}
	
	public Collection<RRModel<RRData>> list(){
		return rrms.values();
	}

	protected static RRModelManager instance = null;
	
	public static RRModelManager get(){
		if (instance == null){
			synchronized(RRModelManager.class){
				if (instance == null){
					instance = new RRModelManager();
				}
			}
		}
		return instance;
	}
}
